//
//  TableSection.swift
//  Risac
//
//  Created by remy on 2018/3/22.
//

import UIKit

open class TableSectionItem: NSObject {
    
    public var model: Any?
    public var index: Int?
    public var cellItems: [TableCellItem] = []
    /// 通过showCellItems显示/隐藏cellItems
    /// # 使用reloadSections更新视图
    /// # 不更新数据而使用insertRows,deleteRows更新视图会crash
    public var showCellItems: Bool = true
    public fileprivate(set) weak var sectionHeader: TableSection?
    public fileprivate(set) weak var sectionFooter: TableSection?
    public var sectionHeaderClass: TableSection.Type?
    public var sectionFooterClass: TableSection.Type?
    public var sectionHeaderTitle: String?
    public var sectionFooterTitle: String?
    public var sectionHeaderHeight: CGFloat?
    public var sectionFooterHeight: CGFloat?
    public var sectionHeaderReuseIDSuffix: String = ""
    public var sectionFooterReuseIDSuffix: String = ""
    open func reload() {}
}

open class TableSection: UITableViewHeaderFooterView {
    
    public var sectionItem: TableSectionItem? {
        didSet {
            if let item = sectionItem {
                if self.metaTypeName == item.sectionHeaderClass?.metaTypeName {
                    item.sectionHeader = self
                } else if self.metaTypeName == item.sectionFooterClass?.metaTypeName {
                    item.sectionFooter = self
                }
            }
            if let item = oldValue {
                if item.sectionHeader == self {
                    item.sectionHeader = nil
                } else if item.sectionFooter == self {
                    item.sectionFooter = nil
                }
            }
        }
    }
    
    func updateBinding(sectionItem: TableSectionItem?) {
        self.sectionItem = sectionItem
        UIView.performWithoutAnimation {
            updateSection(sectionItem: sectionItem)
        }
    }
    
    open func updateSection(sectionItem: TableSectionItem?) {}
    
    open override func prepareForReuse() {
        self.sectionItem = nil
        super.prepareForReuse()
    }
}
